﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;

namespace VSM
{
    public partial class InventoryTransfer : System.Web.UI.Page
    {
        #region Fields
        //public static DataTable dtContents;
        //public static DataTable dtHeader;
        //private static GeneralFunctions GF = null;

        private string TblHeaderName = "OWTR";
        private string TblLineName = "WTR1";
        private string CurrentPageUrl = "/Business/Inventory/InventoryTransfer.aspx";

        private string HeaderKeyName = "DocEntry";
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.Private);

            if (Session[Utils.AppConstants.ID_User] == null
                || Session[Utils.AppConstants.Password] == null
                || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("../../Login.aspx");
            }

            if (!IsPostBack)
            {
                ClearScreen();

                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                Session["TFGF"] = GF;

                String itransId = Request.QueryString["itrans_id"];
                if (!String.IsNullOrEmpty(itransId))
                {
                    LoadData(itransId, ConvertDocType.Get2String(DocType.TRANSFER));
                    SetScreenStatus("Close");
                }
                else
                {
                    LoadDefault();
                    SetScreenStatus("New");
                }

                String BaseEntry = Request.QueryString["base_entry"];
                if (!String.IsNullOrEmpty(BaseEntry))
                {
                    String BaseType = Request.QueryString["base_type"];
                    LoadData(BaseEntry, BaseType);
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvWTR1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvWTR1.PageIndex = e.NewPageIndex;
            DataTable tblITrans = (DataTable)Session["WTR1Table"];
            BindData(tblITrans);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tblITrans = (DataTable)Session["WTR1Table"];
                if (tblITrans != null)
                {
                    DataRow[] rupdate = tblITrans.Select("No=" + lblNo.Text );
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString())) dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                        }
                        tblITrans.Rows.Remove(rupdate[0]);
                        int liNo = 1;
                        foreach (DataRow dr in tblITrans.Rows) // reset detail No. line
                        {
                            dr["No"] = liNo;
                            liNo++;
                        }
                    }
                    this.grvWTR1.EditIndex = -1;
                    BindData((DataTable)Session["WTR1Table"]);
                    CalcTotal(((DataTable)Session["WTR1Table"]));
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        /// <param name="sender"></param>
        protected void grvWTR1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";

                GeneralFunctions GF = (GeneralFunctions)Session["TFGF"];
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                // Load Model
                DropDownList ddlModel = (DropDownList)e.Row.FindControl("ddlModel");
                HiddenField hdnModel = (HiddenField)e.Row.FindControl("hdnModel");
                if (ddlModel != null)
                {
                    ddlModel.DataSource = GF.GetModelList(dbType);
                    ddlModel.DataValueField = "Code";
                    ddlModel.DataTextField = "Name";
                    ddlModel.DataBind();
                    ddlModel.Items.Insert(0, "");
                    if (hdnModel != null) ddlModel.SelectedValue = hdnModel.Value;
                }
                // Load Product
                DropDownList ddlProduct = (DropDownList)e.Row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, hdnModel.Value);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");
                    HiddenField hdnProduct = (HiddenField)e.Row.FindControl("hdnProduct");
                    if (hdnProduct != null) ddlProduct.SelectedValue = hdnProduct.Value;
                }
                // Load Color
                DropDownList ddlColor = (DropDownList)e.Row.FindControl("ddlColor");
                if (ddlColor != null)
                {
                    ddlColor.DataSource = GF.GetColorList(dbType);
                    ddlColor.DataValueField = "Code";
                    ddlColor.DataTextField = "Name";
                    ddlColor.DataBind();
                    ddlColor.Items.Insert(0, "");
                    HiddenField hdnColor = (HiddenField)e.Row.FindControl("hdnColor");
                    if (hdnColor != null) ddlColor.SelectedValue = hdnColor.Value;
                }
            }
        }

  
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GeneralFunctions GF = (GeneralFunctions)Session["TFGF"];
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;

                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtQuantity");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tblITrans = (DataTable)Session["WTR1Table"];

                if (tblITrans != null)
                {
                    DataRow[] rupdate = tblITrans.Select("No=" + lblNo.Text );
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = GF.FormatNumeric(GF.ResetFormatNumeric(txtQuantity.Text), "QtyDec");
                    }
                }

                this.grvWTR1.EditIndex = -1;

                BindData(tblITrans);
                CalcTotal(tblITrans);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            Session["WTR1Table"] = tblData;
            this.grvWTR1.DataSource = tblData;
            this.grvWTR1.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                    DataTable tblITrans = (DataTable)Session["WTR1Table"];
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    GridViewRow grdvRow = null;

                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectItem":
                            this.lblError.Visible = false;
                            if (tblITrans != null)
                            {
                                Dictionary<string, string> dicItem = Session["ChosenItem"] != null ? (Dictionary<string, string>)Session["ChosenItem"] : null;
                                if (dicItem != null)
                                {
                                    foreach (KeyValuePair<string, string> item in dicItem)
                                    {
                                        DataRow rowNew = tblITrans.NewRow();
                                        rowNew["No"] = (tblITrans.Rows.Count + 1).ToString();
                                        rowNew["ItemCode"] = item.Key;
                                        rowNew["Dscription"] = item.Value;
                                        rowNew["U_Model"] =
                                        rowNew["U_Product"] =
                                        rowNew["U_Color"] = string.Empty;
                                        rowNew["Quantity"] = 1;
                                        rowNew["FromWhsCod"] = txtFromWhsCode.Text.Trim();
                                        rowNew["WhsCode"] = txtToWhsCode.Text.Trim();
                                        tblITrans.Rows.Add(rowNew);
                                    }
                                }
                            }
                            //ReLoad Data
                            BindData(tblITrans);
                            break;

                        case "SelectBP":
                            ViewState["rowindex"] = -1;
                            this.lblError.Visible = false;
                            grdvRow = Session["ChosenBP"] != null ? (GridViewRow)Session["ChosenBP"] : null;

                            this.txtCustomerCode.Text = ((Label)grdvRow.FindControl("lblCardCode")).Text;
                            this.txtCustomerName.Text = ((Label)grdvRow.FindControl("lblCardName")).Text;
                            this.txtContactPerson.Text = ((Label)grdvRow.FindControl("lblCntctPrsn")).Text;
                            if (tblITrans != null) tblITrans.Rows.Clear();
                            Session["ChosenBP"] = null;
                            this.btnAddAccessories.Enabled =
                            this.btnAddItems.Enabled = true;
                            break;

                        case "SelectWhsFrom":
                            this.lblError.Visible = false;
                            grdvRow = Session["ChosenWhs"] != null ? (GridViewRow)Session["ChosenWhs"] : null;
                            this.txtFromWhsCode.Text = ((Label)grdvRow.FindControl("lblWhsCode")).Text;
                            this.txtFromWhsName.Text = ((Label)grdvRow.FindControl("lblWhsName")).Text; 

                            Session["ChosenWhs"] = null;
                            break;

                        case "SelectWhsTo":
                            this.lblError.Visible = false;
                            grdvRow = Session["ChosenWhs"] != null ? (GridViewRow)Session["ChosenWhs"] : null;
                            this.txtToWhsCode.Text = ((Label)grdvRow.FindControl("lblWhsCode")).Text;
                            this.txtToWhsName.Text = ((Label)grdvRow.FindControl("lblWhsName")).Text; 
                            Session["ChosenWhs"] = null;
                            break;

                        case "SelectDocList":
                            GridViewRow rowDocList = Session["ChosenDocList"] != null ? (GridViewRow)Session["ChosenDocList"] : null;
                            string DocEntry = ((Label)rowDocList.FindControl("lblDocNum")).Text;
                            string doctype = ((Label)rowDocList.FindControl("lblDocType")).Text;
                            LoadData(DocEntry, doctype);
                            break;

                        case "SelectOSRI":
                            GridViewRow rowOSRI = Session["ChosenOSRI"] != null ? (GridViewRow)Session["ChosenOSRI"] : null;
                            Label lblItemCode = (Label)rowOSRI.FindControl("lblItemCode");
                            Label lblIntrSerial = (Label)rowOSRI.FindControl("lblIntrSerial");
                            Label lblInDate = (Label)rowOSRI.FindControl("lblInDate");
                            Label lblNotes = (Label)rowOSRI.FindControl("lblNotes");
                            Label lblSysSerial = (Label)rowOSRI.FindControl("lblSysSerial");
                            if (tblITrans != null & tblITrans.Rows.Count > 0)
                            {
                                DataRow[] rCheck = tblITrans.Select("ItemCode='" + lblItemCode.Text + "'");
                                if (rCheck.Length == 1)
                                {
                                    rCheck[0]["SysNumber"] = lblSysSerial.Text;
                                    rCheck[0]["DistNumber"] = lblIntrSerial.Text;
                                    rCheck[0]["InDate"] = lblInDate.Text;
                                    rCheck[0]["Notes"] = lblNotes.Text;
                                }

                                // Reload data
                                BindData(tblITrans);
                            }
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        //private DataTable AddNewItem(DataTable tblITrans, DataRow drDefaultLine, string ItemCode, string Dscription, string Model, string Color)
        //{
        //    try
        //    {
        //        if (drDefaultLine != null && drDefaultLine.ItemArray.Length > 0)
        //        {
        //            DataRow rowNew = tblITrans.NewRow();
        //            rowNew["ItemCode"] = (tblITrans.Rows.Count + 1).ToString();
        //            rowNew["ItemCode"] = ItemCode;
        //            rowNew["Dscription"] = Dscription;
        //            rowNew["U_Model"] = Model;
        //            rowNew["U_Color"] = Color;
        //            rowNew["Quantity"] = 1;

        //            rowNew["FromWhsCod"] = txtFromWhsCode.Text;
        //            rowNew["WhsCode"] = txtToWhsCode.Text;

        //            DataRow[] rCheck = tblITrans.Select("ItemCode='" + ItemCode + "'");
        //            if (rCheck.Length == 0)
        //            {
        //                tblITrans.Rows.Add(rowNew);
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        this.lblError.Text = ex.Message;
        //        this.lblError.Visible = true;
        //    }
        //    return tblITrans;
        //}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tb"></param>
        private void CalcTotal(DataTable tb)
        {
            try
            {
                double documentTotal = 0;
                double gstTotal = 0;
                double subTotal = 0;
                foreach (DataRow row in tb.Rows)
                {
                    subTotal += double.Parse(row["LineTotal"].ToString());
                    if (row["Rate"] != null && row["Rate"].ToString().Length > 0)
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * double.Parse(row["Rate"].ToString())) / 100;
                    }
                    else
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * 8.25) / 100;
                    }
                }
                documentTotal += subTotal + gstTotal;
               
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="poDate"></param>
        /// <param name="itemCode"></param>
        /// <param name="venderCode"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        //private DataSet GetDataItem(DateTime poDate, string itemCode, string venderCode, double quantity)
        //{
        //    try
        //    {
        //        MasterData obj = new MasterData();
        //        DataSet ds = new DataSet();
        //        ds = null; // obj.GetItem(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode, poDate, itemCode, venderCode, quantity);
        //        return ds;
        //    }
        //    catch (Exception ex)
        //    {
        //        this.lblError.Text = ex.Message;
        //        this.lblError.Visible = true;
        //    }
        //    return null;
        //}

 
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvWTR1_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                Label lblNo = myRow.FindControl("lblNo") as Label;
                lblNo.Text = (myRow.RowIndex + 1).ToString();

                if (this.hdnStatus.Value == "C")
                {
                    DropDownList ddlModel = (DropDownList)myRow.FindControl("ddlModel");
                    DropDownList ddlProduct = (DropDownList)myRow.FindControl("ddlProduct");
                    DropDownList ddlColor = (DropDownList)myRow.FindControl("ddlColor");

                    TextBox txtQuantity = (TextBox)myRow.FindControl("txtQuantity");

                    if (ddlModel != null)
                    {
                        ddlModel.Enabled = false;
                        ddlModel.BackColor = System.Drawing.Color.Transparent;
                        ddlModel.BorderStyle = BorderStyle.None;
                    }

                    if (ddlProduct != null)
                    {
                        ddlProduct.Enabled = false;
                        ddlProduct.BackColor = System.Drawing.Color.Transparent;
                        ddlProduct.BorderStyle = BorderStyle.None;
                    }

                    if (ddlColor != null)
                    {
                        ddlColor.Enabled = false;
                        ddlColor.BackColor = System.Drawing.Color.Transparent;
                        ddlColor.BorderStyle = BorderStyle.None;
                    }

                    if (txtQuantity != null)
                    {
                        txtQuantity.ReadOnly = true;
                        txtQuantity.BackColor = System.Drawing.Color.Transparent;
                        txtQuantity.BorderStyle = BorderStyle.None;
                    }
                }
            }
        }

        protected void ddlModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
                if (ddlModel.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Model');", true);
                    ddlModel.Focus();
                    return;
                }
                HiddenField hdnModel = (HiddenField)row.FindControl("hdnModel");
                hdnModel.Value = ddlModel.SelectedValue;

                // Load Product
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    ddlProduct.DataSource = ((GeneralFunctions)Session["TFGF"]).GetProductByModel(dbType, ddlModel.SelectedValue);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");

                    HiddenField hdnProduct = (HiddenField)row.FindControl("hdnProduct");
                    hdnProduct.Value = ddlProduct.SelectedValue;
                    SetItem(row);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Product');", true);
                    ddlProduct.Focus();
                    return;
                }

                HiddenField hdnProduct = (HiddenField)row.FindControl("hdnProduct");
                hdnProduct.Value = ddlProduct.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlColor_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlColor = (DropDownList)row.FindControl("ddlColor");
                if (ddlColor.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Color');", true);
                    ddlColor.Focus();
                    return;
                }

                HiddenField hdnColor = (HiddenField)row.FindControl("hdnColor");
                hdnColor.Value = ddlColor.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        private void SetItem(GridViewRow row)
        {
            DataTable tblWTR1 = (DataTable)Session["WTR1Table"];
            Label lblNo = (Label)row.FindControl("lblNo");
            DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
            DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
            DropDownList ddlCorlor = (DropDownList)row.FindControl("ddlColor");

            if (ddlModel != null && ddlProduct != null && ddlCorlor != null)
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                DataTable dtItem =  ((GeneralFunctions)Session["TFGF"]).GetItem(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlModel.SelectedValue, ddlProduct.SelectedValue, ddlCorlor.SelectedValue);
                GetDefault defaultWS = new GetDefault();
                DataRow[] rowUpdate = null;
                if (dtItem != null && dtItem.Rows.Count == 1)
                {
                    DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                    DataSet defaultInfo = defaultWS.GetDefaultLineInfo(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(),
                        this.txtCustomerCode.Text, dtItem.Rows[0]["ItemCode"].ToString(), 1, poDate, Utils.AppConstants.SALES);
                    if (defaultInfo != null && defaultInfo.Tables != null && defaultInfo.Tables[0].Rows.Count == 1)
                    {
                        DataRow drDefaultLine = defaultInfo.Tables[0].Rows[0];
                        rowUpdate = tblWTR1.Select("No=" + lblNo.Text);
                        if (rowUpdate.Length == 1)
                        {
                            rowUpdate[0]["ItemCode"] = dtItem.Rows[0]["ItemCode"].ToString();
                            rowUpdate[0]["Dscription"] = dtItem.Rows[0]["ItemName"].ToString();
                            rowUpdate[0]["Price"] = drDefaultLine["WholeSalePrice"];
                            rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                            rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                            rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                            rowUpdate[0]["Quantity"] = 1;
                        }
                    }
                }
                else
                {
                    rowUpdate = tblWTR1.Select("No=" + lblNo.Text);
                    rowUpdate[0]["ItemCode"] =
                    rowUpdate[0]["Dscription"] = string.Empty;
                    rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                    rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                    rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                    rowUpdate[0]["Price"] = 0;
                    rowUpdate[0]["Quantity"] = 1;
                }
                BindData(tblWTR1);

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtPODate_TextChanged(object sender, EventArgs e)
        {
            try
            {
                //Check Valid Date
               Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text.Trim());
               //this.btnShowPopup.Enabled = true;
            }
            catch
            {
                //this.btnShowPopup.Enabled = false;
            }
        }
        /// <summary>
        /// 
        /// </summary>
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtPostingDate.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Posting Date.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    return;
                }

                if (string.IsNullOrEmpty(txtDocDate.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Document Date.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    return;
                }

                if (string.IsNullOrEmpty(txtCustomerCode.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Customer Code.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    return;
                }

                if (string.IsNullOrEmpty(txtFromWhsCode.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing From Warehouse Code.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    return;
                }

                if (string.IsNullOrEmpty(txtToWhsCode.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing To Warehouse Code.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    return;
                }

                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                String requestXML = _collectData();
                if (requestXML == "") return;

                Transaction ts = new Transaction();
                DataSet ds = ts.CreateMarketingDocument(requestXML, ((ulong)DocType.TRANSFER).ToString(), txtTransferNo.Text, false, dbType);

                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXML;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                //SetControlsStatus("Save");
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseCancel(true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnClose_Click(object sender, EventArgs e)
        {
            CloseCancel(false);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isClose"></param>
        private void CloseCancel(bool isClose)
        {
            try
            {
                Transaction ts = new Transaction();
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM) ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                DataSet ds = ts.CloseCancelDocument(ConvertDocType.Get2String(DocType.TRANSFER), txtTransferNo.Text, isClose, dbType);

                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }

        private void BuildSRNT(ref DataTable dtSRNT, string ItemCode, string SysNumber, string DistNumber, string InDate, string Notes,
            double Quantity, string WhsCode, string DocType, string DocEntry, string DocLineNum)
        {
            if (dtSRNT == null)
            {
                dtSRNT = new DataTable("SRNT");
                dtSRNT.Columns.Add("ItemCode");
                dtSRNT.Columns.Add("SysNumber");    // Default
                dtSRNT.Columns.Add("DistNumber");   // VIN Number
                dtSRNT.Columns.Add("InDate");       // Get default
                dtSRNT.Columns.Add("Quantity");     // 1
                dtSRNT.Columns.Add("WhsCode");      // Default
                dtSRNT.Columns.Add("DocType");      // 13
                dtSRNT.Columns.Add("DocEntry");     // Get from Incoming Payment No.
                dtSRNT.Columns.Add("DocLineNum");   // 1
                dtSRNT.Columns.Add("Notes");   // 
                //dtSRNT.Columns.Add("BSubLineNo");   // LineNo
            }

            DataRow drSRNT = dtSRNT.NewRow();
            drSRNT["ItemCode"] = ItemCode;      // INV1
            drSRNT["SysNumber"] = SysNumber;
            drSRNT["DistNumber"] = DistNumber;   // VIN Number
            drSRNT["InDate"] = Utils.AppConstants.ConvertToDate(InDate).ToString("yyyymmdd");           // Get default
            drSRNT["Quantity"] = Quantity;       // INV1
            drSRNT["WhsCode"] = WhsCode;         // INV1
            drSRNT["DocType"] = DocType;         // INV1
            drSRNT["DocEntry"] = DocEntry;       // INV1
            drSRNT["DocLineNum"] = DocLineNum;   // INV1
            drSRNT["Notes"] = Notes;
            //drSRNT["BSubLineNo"] = BSubLineNo;   // INV1

            dtSRNT.Rows.Add(drSRNT);
        }

        public String _collectData()
        {
            try
            {
                //Update table header
                DataTable dtHeader = new DataTable("OWTR");
                //dtHeader.Columns.Add("DocEntry");
                //dtHeader.Columns.Add("DocNum");
                dtHeader.Columns.Add("Series"); // 21
                dtHeader.Columns.Add("DocDate");
                dtHeader.Columns.Add("TaxDate");
                dtHeader.Columns.Add("CardCode");
                dtHeader.Columns.Add("CardName");
                dtHeader.Columns.Add("U_SOType");
                dtHeader.Columns.Add("Comments");
                dtHeader.Columns.Add("Filler");
                dtHeader.Columns.Add("ToWhsCode");
                // UDF
                dtHeader.Columns.Add("U_ContactPerson");
                dtHeader.Columns.Add("U_DealerID");
                dtHeader.Columns.Add("U_Department");

                DataRow drHeader = dtHeader.NewRow();
                drHeader["Series"] = 21;
                
                drHeader["DocDate"] = Utils.AppConstants.ConvertToDate(txtPostingDate.Text).ToString("yyyyMMdd");
                drHeader["TaxDate"] = Utils.AppConstants.ConvertToDate(txtDocDate.Text).ToString("yyyyMMdd");
                drHeader["Comments"] = txtRemarks.Text;
                //dr["JrnlMemo"] = txtJournalRemark.Text;
                drHeader["CardCode"] = txtCustomerCode.Text;
                drHeader["CardName"] = txtCustomerName.Text;
                drHeader["U_SOType"] = ddl_TransferType.SelectedValue;
                drHeader["Filler"] = txtFromWhsCode.Text;
                drHeader["ToWhsCode"] = txtToWhsCode.Text;
                // UDF
                drHeader["U_ContactPerson"] = txtContactPerson.Text.Trim();
                drHeader["U_DealerID"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                drHeader["U_Department"] = Utils.AppConstants.SALES;

                dtHeader.Rows.Add(drHeader);

                DocumentXML objInfo = new DocumentXML();
                DataSet ds = new DataSet("DS");
                dtHeader.TableName = TblHeaderName;
                ds.Tables.Add(dtHeader.Copy());

                DataTable dtContents = (DataTable)Session["WTR1Table"];
                dtContents.TableName = TblLineName;
                
                DataTable dt = new DataTable("WTR1");
                dt.Columns.Add("LineNum");
                dt.Columns.Add("ItemCode");
                dt.Columns.Add("Dscription");
                dt.Columns.Add("U_Model");
                dt.Columns.Add("U_Product");
                dt.Columns.Add("U_Color");
                dt.Columns.Add("FromWhsCod");
                dt.Columns.Add("WhsCode");
                dt.Columns.Add("Quantity");
                dt.Columns.Add("Price");
                dt.Columns.Add("UomCode");

                DataTable dtSRNT = null;
                if (!String.IsNullOrEmpty(hdnBaseType.Value))
                {
                    dt.Columns.Add("BaseEntry");
                    dt.Columns.Add("BaseLine");
                    dt.Columns.Add("BaseType");
                }

                int liNo = 0;
                foreach (DataRow dr in dtContents.Rows)
                {
                    DataRow rowNew = dt.NewRow();
                    
                    rowNew["LineNum"] = liNo;
                    rowNew["ItemCode"] = dr["ItemCode"];
                    rowNew["Dscription"] = dr["Dscription"];
                    rowNew["U_Model"] = dr["U_Model"];
                    rowNew["U_Product"] = dr["U_Product"];
                    rowNew["U_Color"] = dr["U_Color"];
                    rowNew["FromWhsCod"] = txtFromWhsCode.Text;
                    rowNew["WhsCode"] = txtToWhsCode.Text;
                    rowNew["Quantity"] = dr["Quantity"];
                    rowNew["Price"] = dr["Price"];
                    rowNew["UomCode"] = dr["UomCode"];

                    if (!String.IsNullOrEmpty(hdnBaseType.Value))
                    {
                        rowNew["BaseEntry"] = dr["BaseEntry"];
                        rowNew["BaseLine"] = dr["BaseLine"];
                        rowNew["BaseType"] = dr["BaseType"];
                    }
                    GeneralFunctions GF = (GeneralFunctions)Session["TFGF"];
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM) ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

                    if (!GF.GetItemGroupByCode(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), dr["ItemCode"].ToString()).Equals("104"))
                        BuildSRNT(ref dtSRNT, dr["ItemCode"].ToString(), dr["SysNumber"].ToString(), dr["DistNumber"].ToString(), dr["Indate"].ToString(), dr["Notes"].ToString(),
                                double.Parse(dr["Quantity"].ToString()), dr["WhsCode"].ToString(), ConvertDocType.Get2String(DocType.TRANSFER), txtTransferNo.Text, liNo.ToString());

                    dt.Rows.Add(rowNew);
                    liNo++;
                }

                ds.Tables.Add(((GeneralFunctions)Session["TFGF"]).ResetFormatNumeric(dt, new string[] { "Quantity" }).Copy());
                ds.Tables.Add(dtSRNT.Copy());

                return objInfo.ToXMLStringFromDS( ConvertDocType.Get2String(DocType.TRANSFER), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }

        private DataTable BuildContents(DataTable dtContent)
        {
            GeneralFunctions GF = (GeneralFunctions)Session["TFGF"];
            DataTable dt = new DataTable("WTR1");

            dt.Columns.Add("No");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Dscription");
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Product");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("UomCode");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("OpenQty");
            dt.Columns.Add("Price");
            dt.Columns.Add("FromWhsCod");
            dt.Columns.Add("WhsCode");

            // VIN Number (Serial Number)
            dt.Columns.Add("SysNumber");
            dt.Columns.Add("DistNumber");
            dt.Columns.Add("InDate");
            dt.Columns.Add("Notes");

            dt.Columns.Add("DocEntry");
            dt.Columns.Add("LineNum");
            dt.Columns.Add("BaseType");
            dt.Columns.Add("BaseEntry");
            dt.Columns.Add("BaseLine");

            if (dtContent != null)
            {
                foreach (DataRow dr in dtContent.Rows)
                {
                    DataRow row = dt.NewRow();
                    row["No"] = dr["No"];
                    row["ItemCode"] = dr["ItemCode"];
                    row["Dscription"] = dr["Dscription"];
                    row["U_Model"] = dr["U_Model"];
                    row["U_Product"] = dr["U_Product"];
                    row["U_Color"] = dr["U_Color"];
                    row["UomCode"] = dr["UomCode"];
                    row["Quantity"] = GF.FormatNumeric(GF.ResetFormatNumeric(dr["Quantity"].ToString()), "QtyDec");
                    row["OpenQty"] = dr["OpenQty"];
                    row["Price"] = dr["Price"];
                    row["FromWhsCod"] = dr["FromWhsCod"];
                    row["WhsCode"] = dr["WhsCode"]; // To Whs Code

                    if (dr.Table.Columns.Contains("DistNumber"))
                    {
                        row["SysNumber"] = dr["SysNumber"];
                        row["DistNumber"] = dr["DistNumber"];
                        row["InDate"] = dr["InDate"];
                        row["Notes"] = dr["Notes"];
                    }

                    row["DocEntry"] = dr["DocEntry"];
                    row["LineNum"] = dr["LineNum"];
                    row["BaseType"] = dr["BaseType"];
                    row["BaseEntry"] = dr["BaseEntry"];
                    row["BaseLine"] = dr["BaseLine"];
                    dt.Rows.Add(row);
                }
            }
            return dt;
        }

        protected void LoadData(String itransId, string NewDocType)
        {
            GeneralFunctions GF = (GeneralFunctions)Session["TFGF"];
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            Transaction ts = new Transaction();
            DataSet returnDoc = null;

            if (NewDocType != ConvertDocType.Get2String(DocType.TRANSFER)) // It's copy from transfer request
                returnDoc = ts.GetMarketingDocument_OpenStatus(NewDocType, itransId, dbType);
            else returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, itransId, dbType);

            if (returnDoc == null) returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, "1", dbType);

            if (returnDoc == null || returnDoc.Tables.Count < 2)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('No record found!','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return;
            }

            DataTable dtHeader = returnDoc.Tables[0];
            DataRow dr = dtHeader.Rows[0];

            this.txtTransferNo.Text = dr["DocNum"].ToString();
            this.txtCustomerCode.Text = dr["CardCode"].ToString();
            this.txtCustomerName.Text = dr["CardName"].ToString();
            this.txtFromWhsCode.Text = dr["Filler"].ToString();
            this.txtToWhsCode.Text = dr["ToWhsCode"].ToString();

            txtPostingDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDate"], new CultureInfo("es-US")));
            txtDocDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["TaxDate"], new CultureInfo("es-US")));
            txtContactPerson.Text = dr["U_ContactPerson"].ToString();
            ddl_TransferType.SelectedValue = dr["U_SOType"].ToString();
            txtRemarks.Text = dr["Comments"].ToString();

            if (NewDocType != ConvertDocType.Get2String(DocType.TRANSFER) ) // It's copy from transfer request
                SetScreenStatus("New");
            else SetScreenStatus("Closed");

            DataTable dtContents = BuildContents(returnDoc.Tables[1]);
            hdnBaseType.Value = NewDocType;
            if (NewDocType != ConvertDocType.Get2String(DocType.TRANSFER)) // It's copy from transfer request
            {
                foreach (DataRow row in dtContents.Rows)
                {
                    row["BaseEntry"] = itransId;
                    row["BaseType"] = NewDocType;
                    row["BaseLine"] = row["LineNum"];
                    row["Quantity"] = GF.FormatNumeric(GF.ResetFormatNumeric(row["OpenQty"].ToString()), "QtyDec");
                }
            }
            else
                foreach (DataRow row in dtContents.Rows)
                    row["InDate"] = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(row["InDate"], new CultureInfo("es-US")));
            BindData(dtContents);
        }

        protected void LoadDefault()
        {
            this.txtPostingDate.Text = 
            this.txtDocDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtTransferNo.Text = 
            this.txtCustomerCode.Text = 
            this.txtCustomerName.Text = 
            this.txtContactPerson.Text =
            this.txtRemarks.Text = 
            this.hdnBaseType.Value = string.Empty;
            ddl_TransferType.SelectedValue = "0";

            DataTable dtContents = BuildContents((DataTable)Session["WTR1Table"]);
            BindData(dtContents);
        }

        protected void ClearScreen()
        {
            Session["WTR1Table"] = null;
            CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
            txtPostingDate.Text.ToString(ci);
            txtDocDate.Text.ToString(ci);
            txtFromWhsCode.Text =
            txtFromWhsName.Text = 
            txtToWhsCode.Text = 
            txtToWhsName.Text = 
            txtCustomerCode.Text =
            txtCustomerName.Text =
            txtContactPerson.Text =
            txtRemarks.Text = 
            hdnBaseType.Value = String.Empty;
            ddl_TransferType.SelectedValue = "0";

            //dtContents = new DataTable("WTR1");
            //dtContents.Columns.Add("LineNum");
            //dtContents.Columns.Add("LineStatus");
            //dtContents.Columns.Add("ItemCode");
            //dtContents.Columns.Add("Dscription");
            //dtContents.Columns.Add("Quantity");

            //dtContents.Columns.Add("FromWhsCod");
            //dtContents.Columns.Add("WhsCode");
            //dtContents.Columns.Add("UomCode");
            //dtContents.Columns.Add("U_Model");
            //dtContents.Columns.Add("U_Product");
            //dtContents.Columns.Add("U_Color");

            DataTable dtContents = BuildContents((DataTable)Session["WTR1Table"]);

            BindData(dtContents);
            SetScreenStatus("New");
        }

        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    btnPrintDisplayTransfer.Enabled =
                    btnPrintVehicleTransfer.Enabled =
                    btnPrintTransferInvoice.Enabled =
                    btnAddAccessories.Enabled =
                    btnAddItems.Enabled = false;
                    btnLastRecord.Enabled = 
                    btnSave.Enabled = 
                    btnCopyFrom.Enabled = 
                    btnCancel.Enabled = true;
                    hdnIsUpdate.Value = "false";
                    break;

                case "Update":
                    btnAddAccessories.Enabled =
                    btnPrintDisplayTransfer.Enabled =
                    btnPrintVehicleTransfer.Enabled =
                    btnPrintTransferInvoice.Enabled =
                    btnLastRecord.Enabled =
                    btnAddItems.Enabled = 
                    btnSave.Enabled = 
                    btnCancel.Enabled = 
                    btnCopyFrom.Enabled = true;
                    hdnIsUpdate.Value = "true";
                    break;

                case "Close":
                    btnAddAccessories.Enabled =
                    btnAddItems.Enabled = false;
                    btnSave.Enabled = false;
                    btnPrintDisplayTransfer.Enabled =
                    btnPrintVehicleTransfer.Enabled =
                    btnPrintTransferInvoice.Enabled =
                    btnLastRecord.Enabled =
                    btnCopyFrom.Enabled = true;
                    btnCancel.Enabled = true;
                    break;
            }
            if (Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM))
            {
                btnPrintDisplayTransfer.Visible =
                btnPrintVehicleTransfer.Visible =
                btnPrintTransferInvoice.Visible = true;
            }
            else
            {
                btnPrintDisplayTransfer.Visible =
                btnPrintVehicleTransfer.Visible =
                btnPrintTransferInvoice.Visible = false;
            }
        }

        protected void lnkOSRI_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow gr = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblItemCode = (Label)gr.FindControl("lblItemCode");
                //Label lblWhsCode = (Label)gr.FindControl("lblWhsCode");
                string popup = "OpenOSRI('" + lblItemCode.Text + "','" + txtFromWhsCode.Text.Trim() + "')";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", popup, true);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void btnLastRecord_Click(object sender, EventArgs e)
        {
            GetDefault fGetDefault = new GetDefault();
            string lsTransferNo = fGetDefault.GetMaxDocEntry(
                Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER,
                Session[Utils.AppConstants.ID_Dealer].ToString(),
                Utils.AppConstants.SALES,
                ConvertDocType.Get2String(DocType.TRANSFER),
                TblHeaderName, HeaderKeyName
            );
            if (txtTransferNo.Text.CompareTo(lsTransferNo) != 0) Response.Redirect(CurrentPageUrl + "?itrans_id=" + lsTransferNo);
        }

        protected void btnAddItems_Click(object sender, EventArgs e)
        {
            DataTable tblWTR1 = (DataTable)Session["WTR1Table"];
            DataRow rowNew = tblWTR1.NewRow();
            rowNew["No"] = (tblWTR1.Rows.Count + 1).ToString();
            rowNew["ItemCode"] =
            rowNew["Dscription"] =
            rowNew["U_Model"] =
            rowNew["U_Product"] =
            rowNew["U_Color"] = string.Empty;
            rowNew["Quantity"] = 1;
            rowNew["FromWhsCod"] = txtFromWhsCode.Text.Trim();
            rowNew["WhsCode"] = txtToWhsCode.Text.Trim();

            tblWTR1.Rows.Add(rowNew);
            BindData(tblWTR1);
        }

        protected void btnPrintDisplayTransfer_Click(object sender, EventArgs e)
        {
            ExportExcel(22, "VSM_DisplayTransfer.xls", "DisplayTransfer");
        }

        protected void btnPrintVehicleTransfer_Click(object sender, EventArgs e)
        {
            ExportExcel(21, "VSM_VehicleTransfer.xls", "VehicleTransfer");
        }

        private bool ExportExcel(int beginRow, string tmplateName, string sheetName)
        {
            if (!Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM)) return false;

            try
            {
                GeneralFunctions GF = (GeneralFunctions)Session["TFGF"];
                DataTable dtDisplayTransfer = GF.GetMasterListBySqlCommand(Utils.AppConstants.VSM, "select * from vw_Sal_InventoryTransfer where DocEntry = " + txtTransferNo.Text);
                if (dtDisplayTransfer != null && dtDisplayTransfer.Rows.Count > 0)
                {
                    Utils.NpoiExport npoiExport = new Utils.NpoiExport(this.Server.MapPath(SupportDocs.pathSupportDocsInvoiceTemplate + tmplateName));
                    npoiExport.GetSheet(sheetName);
                    // Collection header data
                    Dictionary<string, object> dic = new Dictionary<string, object>();
                    string lsQty = string.Empty, lsProductNames = string.Empty, lsAccessories = string.Empty; // lsModels = string.Empty,
                    int qty = 0;
                    DataTable dtVehicles = dtDisplayTransfer.Clone();
                    foreach (DataRow dr in dtDisplayTransfer.Rows)
                    {
                        if (!dr["ItemGroup"].ToString().Equals("104"))
                        {
                            dtVehicles.Rows.Add(dr.ItemArray);
                            qty += int.Parse(dr["OpenQty"].ToString());
                            //if (string.IsNullOrEmpty(lsModels)) lsModels = dr["Model"].ToString();
                            //else lsModels += ", " + dr["Model"].ToString();
                            if (string.IsNullOrEmpty(lsProductNames)) lsProductNames = dr["ProductName"].ToString();
                            else lsProductNames += ", " + dr["ProductName"].ToString();
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(lsAccessories)) lsAccessories = dr["Dscription"].ToString();
                            else lsAccessories += ", " + dr["Dscription"].ToString();
                        }
                    }

                    DataRow drHeader = dtVehicles.Rows[0];

                    dic.Add("#DocDate#", Convert.ToDateTime(drHeader["DocDate"].ToString()).ToString("MM/dd/yyyy"));
                    dic.Add("#TransNo#", drHeader["DocEntry"].ToString() + "/" + Convert.ToDateTime(drHeader["DocDate"].ToString()).ToString("yyMM"));
                    dic.Add("#CardCode#", drHeader["CardCode"].ToString());
                    dic.Add("#FromNameAdress#", drHeader["FromNameAdress"].ToString());
                    dic.Add("#Block#", drHeader["Block"].ToString());
                    dic.Add("#ToNameAddress#", drHeader["ToNameAddress"].ToString());
                    dic.Add("#Contact#", drHeader["Contact"].ToString());

                    dic.Add("#QtyModel#", "Số lượng: " + qty.ToString() + " Mitsubishi");
                    dic.Add("#ProductName#", lsProductNames);
                    dic.Add("#Accessories#", lsAccessories);
                    npoiExport.SetValues(dic);

                    // Insert rows in table template
                    npoiExport.InsertTransferDetails(dtVehicles, beginRow, dtVehicles.Rows.Count);

                    // Build xls file name
                    string xlsFileName = "VSM_DisplayTransfer-" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + ".xls";
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + xlsFileName);
                    Response.Clear();
                    Response.BinaryWrite(npoiExport.GetFileHasChanged());
                    Response.End();  
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
                lblError.Enabled = true;
                return false;
            }
            return true;
        }

        protected void btnPrintTransferInvoice_Click(object sender, EventArgs e)
        {
            if (!Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM)) return;
            try
            {
                GeneralFunctions GF = (GeneralFunctions)Session["TFGF"];
                DataTable dtInvTransfer = GF.GetMasterListBySqlCommand(Utils.AppConstants.VSM, "select * from vw_Sal_InternalTransfer_Invoice where DocEntry = " + txtTransferNo.Text);
                if (dtInvTransfer != null && dtInvTransfer.Rows.Count > 0)
                {
                    Utils.NpoiExport npoiExport = new Utils.NpoiExport(this.Server.MapPath(SupportDocs.pathSupportDocsInvoiceTemplate + "VSM_InvoiceTransfer.xls"));
                    npoiExport.GetSheet("InvoiceTransfer");
                    // Collection header data
                    Dictionary<string, object> dic = new Dictionary<string, object>();
                    DataTable dtVehicles = dtInvTransfer.Clone();

                    foreach (DataRow dr in dtInvTransfer.Rows)
                    {
                        if (!dr["ItemGroup"].ToString().Equals("104"))
                        {
                            dtVehicles.Rows.Add(dr.ItemArray);
                            break;
                        }
                    }

                    DataRow drHeader = dtVehicles.Rows[0];

                    dic.Add("#InvDay#", Convert.ToDateTime(drHeader["TaxDate"].ToString()).ToString("dd"));
                    dic.Add("#InvMonth#", Convert.ToDateTime(drHeader["TaxDate"].ToString()).ToString("MM"));
                    dic.Add("#InvYear#", Convert.ToDateTime(drHeader["TaxDate"].ToString()).ToString("yyyy"));
                    dic.Add("#InvNo#", drHeader["DocEntry"].ToString() + "/" + Convert.ToDateTime(drHeader["DocDate"].ToString()).ToString("yyMM"));
                    dic.Add("#FromNameAddress#", drHeader["FromNameAddress"].ToString());
                    dic.Add("#ToNameAddress#", drHeader["ToNameAddress"].ToString());
                    dic.Add("#FrgnName#", drHeader["FrgnName"].ToString());
                    dic.Add("#ProductName#", "Hiệu Mitsubishi " + drHeader["ProductName"].ToString());
                    dic.Add("#Color#", drHeader["Color"].ToString());
                    dic.Add("#DistNumber#", drHeader["DistNumber"].ToString());
                    dic.Add("#Notes#", drHeader["Notes"].ToString());
                    dic.Add("#Price#", GF.FormatNumeric(GF.ResetFormatNumeric(drHeader["Price"].ToString()), "PriceDec"));
                    dic.Add("#TaxAmount#", GF.FormatNumeric(GF.ResetFormatNumeric(drHeader["TaxAmount"].ToString()), "SumDec"));
                    dic.Add("#TotalAmount#", GF.FormatNumeric(GF.ResetFormatNumeric(drHeader["TotalAmount"].ToString()), "SumDec"));

                    long lTotalAmount = long.Parse(drHeader["TotalAmount"].ToString());
                    dic.Add("#TotalAmountByWords#", GF.Amount2Words(lTotalAmount, " đồng"));
                    npoiExport.SetValues(dic);

                    // Build xls file name
                    string xlsFileName = "VSM_InvoiceTransfer-" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + ".xls";
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + xlsFileName);
                    Response.Clear();
                    Response.BinaryWrite(npoiExport.GetFileHasChanged());
                    Response.End();
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
                lblError.Enabled = true;
            }
        }

    }
}